<template>
	<view>
		<!-- 功能性组件，无实际UI -->
	</view>
</template>

<script>
import api from '@/api/index.js'
export default {
	name: 'voice-recorder',
	data() {
		return {
			isRecording: false,
			recordingTime: 0,
			recordingTimer: null,
			isCancel:false,
		}
	},
	mounted() {
		// 检查录音权限
		this.checkRecordPermission()
	},
	beforeDestroy() {
		// 组件销毁时停止录音
		if (this.isRecording) {
			this.stopRecording(false)
		}
	},
	methods: {
		// 检查录音权限
		checkRecordPermission() {
			uni.authorize({
				scope: 'scope.record',
				success: () => {
					console.log('录音权限已获取')
				},
				fail: () => {
					uni.showModal({
						title: '提示',
						content: '需要录音权限才能使用语音输入功能',
						success: (res) => {
							if (res.confirm) {
								uni.openSetting()
							}
						}
					})
				}
			})
		},
		// 开始语音输入
		startVoiceInput(isStart, isCancel) {
			this.isCancel = isCancel
			if (isStart) {
				this.startRecording()
			} else {
				this.stopRecording(isCancel)
			}
		},
		// 开始录音
		startRecording() {
			const recorderManager = uni.getRecorderManager()
			
			recorderManager.onStart(() => {
				console.log('录音开始')
				this.isRecording = true
				this.recordingTime = 0
				// 开始计时
				this.recordingTimer = setInterval(() => {
					this.recordingTime++
					// 超过60秒自动停止
					if (this.recordingTime >= 60) {
						this.stopRecording(false)
					}
				}, 1000)
			})
			
			recorderManager.onStop((res) => {
				console.log('录音结束', res)
				this.isRecording = false
				clearInterval(this.recordingTimer)
				if (this.isCancel) {
					return
				}
				if (res.duration < 1000 ) {
					uni.showToast({
						title: '说话时间太短',
						icon: 'none'
					})
					return
				}
				
				// 上传录音文件进行语音识别
				this.uploadVoiceFile(res.tempFilePath)
			})
			
			recorderManager.onError((res) => {
				console.error('录音错误', res)
				this.isRecording = false
				clearInterval(this.recordingTimer)
				uni.showToast({
					title: '录音失败',
					icon: 'none'
				})
			})
			
			// 开始录音
			recorderManager.start({
				duration: 60000, // 最长录音时间，单位ms
				sampleRate: 16000,
				numberOfChannels: 1,
				encodeBitRate: 48000,
				format: 'mp3'
			})
		},
		// 停止录音
		stopRecording(isCancel) {
			const recorderManager = uni.getRecorderManager()
			recorderManager.stop()
			
			if (isCancel) {
				uni.showToast({
					title: '已取消录音',
					icon: 'none'
				})
			}
		},
		// 上传语音文件进行识别
		async uploadVoiceFile(tempFilePath) {			
			uni.showLoading({
				title: '正在识别...'
			})
			
			try {
				
				const res = await api.voice.voiceToText(tempFilePath)
				console.log('语音识别结果',res);
				if (res) {
					// 将识别结果发送给父组件
					this.$emit('voiceResult', res)
				}
			} catch (error) {
				console.error('语音识别失败:', error)
				uni.showToast({
					title: '语音识别失败',
					icon: 'none'
				})
			} finally {
				uni.hideLoading()
			}
		}
	}
}
</script> 